<template>
  <a-drawer
    v-model:visible="visible"
    :title="modalTitle"
    :closable="false"
    width="75%"
    :footer-style="{ textAlign: 'right' }"
    @close="handleCancel"
  >
    <a-form :model="formState" ref="formRef">
      <a-tabs v-model:activeKey="state.activeKey">
        <a-tab-pane key="1" tab="基础信息" forceRender>
          <a-row type="flex" :gutter="24">
            <a-col :span="12">
              <a-form-item
                label="商品名称"
                name="goods_name"
                :rules="[{ required: true, message: '请输入商品名称' }]"
              >
                <a-input
                  placeholder="请输入商品名称"
                  v-model:value="formState.goods_name"
                  show-count
                  :maxlength="60"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="商品编号" name="goods_no">
                <a-input
                  placeholder="请输入商品编号"
                  v-model:value="formState.goods_no"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="商品分类"
                name="goods_cate"
                :rules="[{ required: true, message: '请选择分类' }]"
              >
                <a-tree-select
                  v-model:value="formState.goods_cate"
                  style="width: 100%"
                  :tree-data="state.cateList"
                  allow-clear
                  treeDefaultExpandAll
                  show-search
                  :show-checked-strategy="SHOW_ALL"
                  placeholder="请选择分类"
                  multiple
                  treeNodeFilterProp="name"
                  :field-names="{
                    children: 'child',
                    label: 'name',
                    value: 'cate_id',
                  }"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="商品服务"
                name="goods_service"
                :rules="[{ required: true, message: '请选择商品服务' }]"
              >
                <a-select
                  v-model:value="formState.goods_service"
                  mode="multiple"
                  placeholder="请选择商品服务"
                  :options="state.ServiceOptions"
                  :field-names="{ label: 'name', value: 'service_id' }"
                ></a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="商品标签" name="goods_label">
                <a-select
                  v-model:value="formState.goods_label"
                  mode="multiple"
                  placeholder="请选择商品标签"
                  :options="state.LabelOptions"
                  :field-names="{ label: 'name', value: 'label_id' }"
                ></a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="是否运行分销提成" name="is_rebate">
                <a-radio-group v-model:value="formState.is_rebate">
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="0">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="新人类型" name="new_type">
                <a-radio-group v-model:value="formState.new_type">
                  <a-radio :value="1">新人1</a-radio>
                  <a-radio :value="2">新人2</a-radio>
                  <a-radio :value="3">新人3</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="商品排序" name="sort" extra="排序从大到小">
                <a-input-number
                  style="width: 200px"
                  v-model:value="formState.sort"
                  placeholder="请输入排序"
                  :min="0"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="虚拟销量" name="goods_unsales">
                <a-input-number
                  style="width: 200px"
                  v-model:value="formState.goods_unsales"
                  :min="0"
                  placeholder="请输入虚拟销量"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="每人限购数量"
                name="limit_num"
                extra="0就是不限购,大于0就限购"
              >
                <a-input-number
                  style="width: 200px"
                  v-model:value="formState.limit_num"
                  :min="0"
                  placeholder="请输入限购数量"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="是否允许自提" name="shop_type">
                <a-radio-group v-model:value="formState.shop_type">
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="0">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="商品店铺"
                name="goods_shop"
                :rules="[
                  {
                    required: formState.shop_type == 1 ? true : false,
                    message: '请选择商品店铺',
                  },
                ]"
              >
                <a-select
                  v-model:value="formState.goods_shop"
                  placeholder="请选择商品店铺"
                  :options="state.ShopOptions"
                  allowClear
                  :field-names="{ label: 'shop_name', value: 'shop_id' }"
                ></a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item
            label="商品图片"
            name="slider_image"
            :rules="[{ required: true, message: '请选择商品图片' }]"
            extra="*第一张图片默认为商品主图，上传的主图需要为正方形，建议尺寸为800*800px，大小在3M以内。"
          >
            <a-form-item-rest>
              <app-upload
                :fileList="formState.slider_image"
                :min="5"
                @upload-img="uploadImg"
              />
            </a-form-item-rest>
          </a-form-item>
        </a-tab-pane>
        <a-tab-pane key="2" tab="商品规格" forceRender>
          <a-form-item
            label="商品规格"
            :rules="[{ required: true, message: '请输入商品规格' }]"
            style="width: 100%"
          >
            <a-button
              type="primary"
              @click="addTable"
              class="flex items-center"
            >
              <template #icon>
                <PlusOutlined /> </template
              >添加商品规格</a-button
            >
            <div class="mt-2">
              <SkuTable
                :dataSource="formState.goods_sku"
                @delete-img="delSkuImg"
                @select-img="selectSkuImg"
                @delete-sku="delGoodsSku"
              />
            </div>
          </a-form-item>
        </a-tab-pane>
        <a-tab-pane key="3" tab="商品参数" forceRender>
          <a-form-item label="商品参数">
            <a-button
              type="primary"
              @click="addGoodsParams"
              class="flex items-center"
            >
              <template #icon>
                <PlusOutlined /> </template
              >添加商品参数</a-button
            >
            <div class="mt-3">
              <ParamsTable
                :dataSource="formState.goods_params"
                @delete="handleDelParams"
              />
            </div>
          </a-form-item>
        </a-tab-pane>
        <a-tab-pane key="4" tab="商品简介" forceRender>
          <a-form-item label="商品简介">
            <Editor
              :content="formState.goods_brief"
              @getContent="getGoodsBrief"
            ></Editor>
          </a-form-item>
        </a-tab-pane>
        <a-tab-pane key="5" tab="详情介绍" forceRender>
          <a-form-item
            label="详情介绍"
            :rules="[{ required: true, message: '请输入详情介绍' }]"
          >
            <Editor
              :content="formState.content"
              @getContent="getContent"
            ></Editor>
          </a-form-item>
        </a-tab-pane>
      </a-tabs>
    </a-form>
    <template #footer>
      <a-button style="margin-right: 8px" @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleOk">确定</a-button>
    </template>
  </a-drawer>
  <!--选择sku图片-->
  <app-img-drawer ref="imgRef" @drawer-success="appImg" />
</template>
<script setup>
import useModal from "@/utils/useModal";
import { reactive, ref } from "vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import { message, TreeSelect } from "ant-design-vue";
import { treeCate as getCateList } from "@/api/goods/cate";
import { add, edit } from "@/api/goods/goods";
import { all as getAllLabel } from "@/api/goods/label";
import { all as getAllService } from "@/api/goods/service";
import { all as getAllNewer } from "@/api/goods/newer";
import { getShop } from "@/api/home";
const { visible, modalTitle } = useModal();

const emits = defineEmits(["model-success"]);
const SHOW_ALL = TreeSelect.SHOW_ALL;

const formRef = ref();
const imgRef = ref();

const formState = reactive({
  goods_name: "",
  goods_cate: [],
  goods_service: [],
  goods_label: [],
  new_type: 0,
  newer_id: null, // 新人活动
  is_rebate: null,
  shop_type: 0, //是否允许自提
  goods_type: 1, //商品类型
  content: "",
  slider_image: [],
  sort: 0,
  goods_no: "",
  goods_unsales: 0,
  limit_num: 0,
  goods_params: [],
  goods_sku: [],
  goods_brief: "",
  goods_shop: null, //商品店铺
});
const state = reactive({
  cateList: [], //分类列表
  activeKey: "1", //tab切换的
  skuIndex: 0, //选择sku的图片
  LabelOptions: [],
  NewerOptions: [],
  ServiceOptions: [],
  ShopOptions: [],
});
const show = (model) => {
  modalTitle.value = model.title;
  state.activeKey = "1";
  getAllNewerList();
  getAllCateList();
  getAllLabelList();
  getAllServiceList();
  getShopList();
  visible.value = true;
  formState.newer_id = model.newer_id;
  formState.goods_type = model.goods_type;
};
const getAllLabelList = () => {
  getAllLabel().then((res) => {
    if (res.code == 0) state.LabelOptions = res.data;
  });
};
const getAllServiceList = () => {
  getAllService().then((res) => {
    if (res.code == 0) state.ServiceOptions = res.data;
  });
};
// 获取店铺列表
const getShopList = () => {
  getShop().then((res) => {
    if (res.code == 0) state.ShopOptions = res.data.data || [];
  });
};
// 获取所有新人活动
const getAllNewerList = () => {
  getAllNewer().then((res) => {
    if (res.code == 0) state.NewerOptions = res.data || [];
  });
};
const addGoodsParams = () => {
  const newData = {
    title: "",
    content: "",
  };
  formState.goods_params = [...formState.goods_params, newData];
};
const handleDelParams = (index) => {
  formState.goods_params.splice(index, 1);
};
//选择规格的图片
const selectSkuImg = (index) => {
  state.skuIndex = index;
  imgRef.value.show();
};
const addTable = () => {
  const newData = {
    sku_name: "",
    goods_price: "",
    cost_price: "",
    market_price: "",
    stock_num: "",
    sku_img: "",
  };
  formState.goods_sku = [...formState.goods_sku, newData];
};
const uploadImg = (item) => {
  formState.slider_image = formState.slider_image.concat(item);
};
const delGoodsSku = (index) => {
  formState.goods_sku.splice(index, 1);
};
const delSkuImg = (index) => {
  formState.goods_sku[index].sku_img = "";
};
const getGoodsBrief = (values) => {
  formState.goods_brief = values;
};
const getContent = (values) => {
  formState.content = values;
};
const appImg = (val) => {
  formState.goods_sku[state.skuIndex].sku_img = val[0];
};
//获取分类
const getAllCateList = () => {
  getCateList().then(function (res) {
    if (res.code == 0) {
      const data = res.data;
      state.cateList = data.map((item) => {
        return {
          ...item,
          disabled: item.status == 0 ? true : false,
          children:
            item.child?.map((ele) => {
              return {
                ...ele,
                disabled: ele.status == 0 ? true : false,
              };
            }) || [],
        };
      });
    }
  });
};
// 保存
const handleOk = async () => {
  await formRef.value.validate().then(() => {
    const params = {
      ...formState,
      slider_image: formState.slider_image?.map((item) => item.url),
    };
    if (formState.goods_id) {
      edit({
        id: formState.goods_id,
        ...params,
      }).then(function (res) {
        if (res.code == 0) {
          message.success(res.msg);
          handleCancel();
          emits("model-success");
        }
      });
    } else {
      //添加
      add(params).then(function (res) {
        if (res.code == 0) {
          message.success(res.msg);
          handleCancel();
          emits("model-success");
        }
      });
    }
  });
};
const handleCancel = () => {
  visible.value = false;
  formRef.value.resetFields();
};
defineExpose({
  show,
});
</script>